//
//  GKSearchViewController.m
//  jinyishe
//
//  Created by xiaoxiaoniuzai on 2017/11/10.
//  Copyright © 2017年 wy. All rights reserved.
//

#import "GKSearchViewController.h"
#import "driveSchoolCell.h"
#import "NetworkManager.h"
#import "driveSchoolModel.h"
#import "UIView+Enlarge.h"
#import "driveDetialVC.h"
#define historyDataKey @"historyDataKey"

@interface GKSearchViewController ()<UISearchBarDelegate>

@property (nonatomic, strong) UIView *historyView;
@property (nonatomic, strong) UIView *navigationView;
@property (nonatomic, strong) UISearchBar *searchBar;

@property (nonatomic, copy) NSMutableArray *historyDatas;

@end

@implementation GKSearchViewController {
    
    UIView *_historyLabelView;
}

- (instancetype)init {
    
    if (self = [super initWithStyle:UITableViewStyleGrouped]) {
        self.view.backgroundColor = [UIColor custom_color:@"#F7F7F7"];
    }
    return self;
}

- (UIView *)navigationView {
    if (!_navigationView) {
        _navigationView = [UIView new];
        _navigationView.frame = CGRectMake(0, 0, self.view.frame.size.width, StatusBarAndNavigationBarHeight);
        _navigationView.backgroundColor = [UIColor custom_color:@"#F7F7F7"];
        [self.view addSubview:_navigationView];
    }
    return _navigationView;
}

- (NSMutableArray *)historyDatas {
    
    if (!_historyDatas) {
        _historyDatas = [NSMutableArray array];
    }
    return _historyDatas;
}

- (UISearchBar *)searchBar {
    
    if (!_searchBar) {
        
        _searchBar = [[UISearchBar alloc] init];
        _searchBar.frame = CGRectMake(0, StatusBarHeight + 8, self.view.frame.size.width, 28);
        _searchBar.placeholder = @"搜索附近驾校";
        _searchBar.showsCancelButton = YES;
        _searchBar.delegate = self;
        [self adjustSearchBarProperty: _searchBar];
    }
    return _searchBar;
}

- (UIView *)historyView {
    
    if (!_historyView) {
        _historyView = [[UIView alloc] initWithFrame:CGRectMake(0, StatusBarAndNavigationBarHeight, self.view.frame.size.width, self.view.frame.size.height - TabbarSafeBottomMargin - StatusBarAndNavigationBarHeight)];
        _historyView.backgroundColor = [UIColor whiteColor];
        
        UILabel *titleLable = [[UILabel alloc] init];
        titleLable.frame = CGRectMake(12, 18, 100, 20);
        titleLable.text = @"历史搜索";
        titleLable.font = [UIFont systemFontOfSize:14];
        titleLable.textColor = [UIColor black_666666];
        [_historyView addSubview:titleLable];
        
        UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        deleteBtn.frame = CGRectMake(_historyView.frame.size.width - 16 - 12, 0, 16, 16);
        deleteBtn.center = CGPointMake(deleteBtn.center.x, titleLable.center.y);
        [deleteBtn setImage:[UIImage imageNamed:@"home_ico_delete"] forState:UIControlStateNormal];
        [deleteBtn setEnlargeEdgeWithTop:5 right:5 bottom:5 left:5];
        [deleteBtn addTarget:self action:@selector(deleteDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [_historyView addSubview:deleteBtn];
        
        UIView *historyLabelView = [[UIView alloc] init];
        historyLabelView.frame = CGRectMake(12, CGRectGetMaxY(titleLable.frame) + 16, _historyView.frame.size.width - 24, 160);
        historyLabelView.tag = 1005;
        [self addHistoryDataTo: historyLabelView];
        _historyLabelView = historyLabelView;
        historyLabelView.clipsToBounds = YES;
        [_historyView addSubview:historyLabelView];
        
    }
    return _historyView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSArray *historys = [[NSUserDefaults standardUserDefaults] objectForKey:historyDataKey];
    if (historys) {
        [self.historyDatas addObjectsFromArray:historys];
    }
    
    [self.navigationView addSubview:self.searchBar];
    [self.view addSubview:self.historyView];
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.navigationView.mas_bottom);
        if (kScreenHeight == 812) {
            make.bottom.equalTo(self.view.mas_bottom).offset(-34);
        } else {
            make.bottom.equalTo(self.view.mas_bottom);
        }
    }];
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0 );
        
    } else {
        self.tableView.contentInset = UIEdgeInsetsMake(-20, 0, 0, 0 );
    }
}

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = NO;
}
- (BOOL)fd_prefersNavigationBarHidden {
    return YES;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
//    self.tableView.frame = CGRectMake(0, StatusBarAndNavigationBarHeight, self.view.frame.size.width, self.view.frame.size.height - TabbarSafeBottomMargin - StatusBarAndNavigationBarHeight);
}

- (void)confingureTableView {
    [super confingureTableView];
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor custom_color:@"#F7F7F7"];
    self.tableView.rowHeight = 137;
    self.tableView.hidden = YES;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([driveSchoolCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([driveSchoolCell class])];
}

- (UIImage *)tableViewEmptyPlaceHolderImage {
    
    return [UIImage imageNamed:@"common_pic_massage"];
}

- (NSAttributedString *)tableViewEmptyTitle {
    
    NSAttributedString *attr = [[NSAttributedString alloc] initWithString:@"没有找到该驾校!" attributes:@{NSForegroundColorAttributeName:[UIColor custom_color:@"#BBBBBB"], NSFontAttributeName:[UIFont systemFontOfSize:14]}];
    return attr;
}

- (void)dismiss {
    
    [self.searchBar resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)deleteDidClick:(UIButton *)btn {
    
    [self.historyDatas removeAllObjects];
    [[NSUserDefaults standardUserDefaults] setObject:self.historyDatas forKey:historyDataKey];
    [_historyLabelView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview) withObject:nil];
}

- (void)addHistoryDataTo:(UIView *)superView {
    
    for (UIView *subView in superView.subviews) {
        [subView removeFromSuperview];
    }
    if (self.historyDatas && self.historyDatas.count > 0) {
        CGFloat columnMargin = 11;
        CGFloat rowMargin = 16;
        CGFloat labelW = (superView.frame.size.width - 22) / 3;
        CGFloat labelH = 28;
        CGFloat labelX = 0;
        CGFloat labelY = 0;
        CGFloat row;
        CGFloat column;
        for (NSInteger index = 0; index < self.historyDatas.count; index ++) {
            UIView *backView = [[UIView alloc] init];
            backView.backgroundColor = [UIColor custom_color:@"#F7F7F7"];
            backView.layer.cornerRadius = 4;
            backView.layer.masksToBounds = YES;
            backView.tag = index;
            column = index % 3;
            row = index / 3;
            labelX = column * (labelW + columnMargin);
            labelY = row * (labelH + rowMargin);
            backView.frame = CGRectMake(labelX, labelY, labelW, labelH);
            
            UILabel *label = [[UILabel alloc] init];
            label.text = self.historyDatas[index];
            label.textColor = [UIColor custom_color:@"#999999"];
            label.font = [UIFont systemFontOfSize:12];
            label.textAlignment = NSTextAlignmentCenter;
            label.frame = CGRectMake(7, 0, backView.frame.size.width - 14, backView.frame.size.height);
            [backView addSubview:label];
            
            [superView addSubview:backView];
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(historyLabelDidClick:)];
            [backView addGestureRecognizer:tap];
        }
    }
}

/** 刷新历史记录 */
- (void)reloadSearchHistoryViewItem
{
    UIView *histyView = [self.historyView viewWithTag:1005];
    [self addHistoryDataTo:histyView];
}


- (void)historyLabelDidClick:(UITapGestureRecognizer *)tap {
    
    NSInteger index = tap.view.tag;
    if (index < self.historyDatas.count) {
        self.searchBar.text = self.historyDatas[index];
        [self.searchBar resignFirstResponder];
        [self getSearchResults:self.historyDatas[index]];
    }
}



// MARK: - 搜索
- (void)getSearchResults:(NSString *)text {
    if (self.laa == nil || self.loo == nil || self.sign == nil || text == nil) {
        [MBProgressHUD gk_toastShowMessage:@"请检查您的网络"];
        return;
    }
    NSDictionary *parames = @{
                @"companyName":text,
                @"longitude":self.loo,
                @"latitude":self.laa,
                @"city":self.sign
                };
    __weak typeof(self) weakSelf = self;
    [[NetworkManager defaultManager] postWithURLString:[[apiManger shareApiManger] drivcList] parameters:parames success:^(id responseObject) {
        __strong typeof(self) strongSelf = weakSelf;
        [strongSelf endFooterRefresh];
        [strongSelf endHeaderRefresh];
        if ([responseObject[@"rcd"] isEqualToString:kNetResponse_R0001]) {
            [strongSelf handleResponseData:responseObject searchText:text];
        }
    } failure:^(NSError *error) {
        [weakSelf endFooterRefresh];
        [weakSelf endHeaderRefresh];
    }];
}

- (void)handleResponseData:(NSDictionary *)responseObject  searchText:(NSString *)text {
    
    [self.dataArray removeAllObjects];
    NSDictionary *dic = responseObject[@"data"];
    NSMutableArray *modelArray = [driveSchoolModel mj_objectArrayWithKeyValuesArray:dic[@"result"]];
    if (modelArray.count) {
        //[modelArray setValue:text forKeyPath:@"searchText"];
        [self.dataArray addObjectsFromArray:modelArray];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        self.historyView.hidden = YES;
        self.tableView.hidden = NO;
        [self.tableView reloadData];
    });
}


// MARK: - UITableViewDelegate & UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 75;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    driveSchoolCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([driveSchoolCell class])];
    cell.model = self.dataArray[indexPath.section];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    driveSchoolModel *infoModel = self.dataArray[indexPath.section];
    driveDetialVC *detial = [driveDetialVC new];
    detial.ID = infoModel.id;
    detial.distance = infoModel.distance;
    [self.navigationController pushViewController:detial animated:YES];
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

// MARK: - UISearchBarDelegate

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
// called when text changes (including clear)
{
    self.historyView.hidden = NO;
    self.tableView.hidden = YES;
    NSArray *historys = [[NSUserDefaults standardUserDefaults] objectForKey:historyDataKey];
    if (historys) {
        [self.historyDatas removeAllObjects];
        [self.historyDatas addObjectsFromArray:historys];
        [self reloadSearchHistoryViewItem];
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    NSLog(@"%@", searchBar.text);
    
    [searchBar resignFirstResponder];
    NSString *searchText = searchBar.text;
    
    [self getSearchResults:searchText];
    
    if ([self.historyDatas containsObject:searchText]) {
        [self.historyDatas removeObject:searchText];
    }
    
    [self.historyDatas insertObject:searchText atIndex:0];
    [[NSUserDefaults standardUserDefaults] setObject:self.historyDatas forKey:historyDataKey];

}


- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    
    [self dismiss];
}


- (void)adjustSearchBarProperty:(UISearchBar *)searchBar {
    
    searchBar.barTintColor = [UIColor gk_colorWithHexString:@"#2E2424"];
    UIView *searchTextField = [[[searchBar.subviews firstObject] subviews] lastObject];
    searchTextField.backgroundColor = searchBar.backgroundColor;
    
    for (UIView *view in searchBar.subviews) {
        if ([view isKindOfClass:NSClassFromString(@"UIView")] && view.subviews.count > 0) {
            [[view.subviews objectAtIndex:0] removeFromSuperview];
             break;
        }
    }
   
    for (id subview in [searchBar.subviews[0] subviews]) {
        NSLog(@"subviwe = %@", subview);
        if ([subview isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *)subview;
            [btn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
            [btn setTitle:@"取消" forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor gk_colorWithHexString:@"#2E2424"] forState:UIControlStateNormal];
            btn.bounds = CGRectMake(btn.bounds.origin.x, btn.frame.origin.y, 100, 20);
            btn.titleLabel.font = [UIFont systemFontOfSize:16];
        }
        if ([subview isKindOfClass:[UITextField class]]) {
            UITextField *searchField = (UITextField *)subview;
            searchField.font = [UIFont systemFontOfSize:12];
        }
    }
    
    for (UIGestureRecognizer *tap in searchBar.gestureRecognizers) {
        [searchBar removeGestureRecognizer:tap];
    }
    
    UITapGestureRecognizer *searchBarTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(searchBarTapAction:)];
    [searchBar addGestureRecognizer:searchBarTapGestureRecognizer];

    
}

- (void)searchBarTapAction:(UITapGestureRecognizer *)tap {
    
    [self dismiss];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
